package com.spring.demo.init.web;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.spring.demo.web.interceptor.TestInterceptor;

@Configuration
@ComponentScan(basePackages = { "com.spring.demo.web" })
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {

	/**
	 * 注入http invoker 调用服务
	 * 
	 * @return
	 */
	@Bean
	public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
		Properties mappings = new Properties();
		mappings.setProperty("httpUserService", "httpInvokerServiceExporter");

		SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
		mapping.setMappings(mappings);

		return mapping;
	}

	/**
	 * 注册拦截器
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new TestInterceptor()).addPathPatterns("/*");
	}

	/**
	 * 静态资源文件映射
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/js/**").addResourceLocations(
				"/WEB-INF/resources/js/");
		registry.addResourceHandler("/css/**").addResourceLocations(
				"/WEB-INF/resources/css/");
	}

	@Bean(name = "messageSource")
	public ResourceBundleMessageSource resourceBundleMessageSource() {
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		messageSource.setBasename("validation/validation");
		messageSource.setDefaultEncoding("UTF-8");
		messageSource.setUseCodeAsDefaultMessage(true);

		return messageSource;
	}

	@Bean
	public InternalResourceViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setViewClass(JstlView.class);
		viewResolver.setPrefix("/WEB-INF/pages/");
		viewResolver.setSuffix(".jsp");

		return viewResolver;
	}

	// @Bean
	// public AnnotationAwareAspectJAutoProxyCreator controllerProxyFactory() {
	// List<String> aspectBeanNames = new ArrayList<String>();
	// aspectBeanNames.add("controllerAspect");
	// AnnotationAwareAspectJAutoProxyCreator proxyFactory = new
	// AnnotationAwareAspectJAutoProxyCreator();
	// proxyFactory.setIncludePatterns(aspectBeanNames);
	//
	// return proxyFactory;
	// }
}
